package com.departmentstore.service.impl;

import com.departmentstore.entity.Department;
import com.departmentstore.repository.DepartmentRepository;
import com.departmentstore.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    private final DepartmentRepository departmentRepository;

    @Autowired
    public DepartmentServiceImpl(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Department createDepartment(Department department) {
        return departmentRepository.save(department);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Department updateDepartment(Department department) {
        if (!departmentRepository.existsById(department.getDepartmentId())) {
            throw new RuntimeException("部门不存在");
        }
        return departmentRepository.save(department);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void deleteDepartment(String departmentId) {
        if (!departmentRepository.existsById(departmentId)) {
            throw new RuntimeException("部门不存在");
        }
        departmentRepository.deleteById(departmentId);
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Department getDepartmentById(String departmentId) {
        return departmentRepository.findById(departmentId)
                .orElseThrow(() -> new RuntimeException("部门不存在"));
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public List<Department> getAllDepartments() {
        return departmentRepository.findAll();
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Department getDepartmentByName(String name) {
        return departmentRepository.findByName(name);
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Department getDepartmentByManagerId(String managerId) {
        return departmentRepository.findByManagerEmployeeId(managerId);
    }
} 